package io.hots.mq;

import com.rabbitmq.client.Channel;
import io.hots.enums.BizCodeEnum;
import io.hots.exception.BizException;
import io.hots.service.ScanCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author yueshibin@cetcbigdata.com
 * @date 2022/6/17 8:51 下午
 */
@Component
@Slf4j
@RabbitListener(queues = "scan_code.user.queue")
public class ScanCodeUserMQListener {

    @Autowired
    ScanCodeService scanCodeService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @RabbitHandler
    public void scanCodeUserHandler(CodeMessage codeMessage, Message message, Channel channel){
        String msgId = message.getMessageProperties().getMessageId();

        String flag = redisTemplate.opsForValue().get(msgId);

        if (flag==null){
            try {
                // 处理业务
                scanCodeService.handlerCode(codeMessage);
                redisTemplate.opsForValue().set(msgId,"1");
            } catch (Exception e) {
                // 处理业务失败
                log.error("消费失败{}", codeMessage);
                e.printStackTrace();
                throw new BizException(BizCodeEnum.MQ_CONSUME_EXCEPTION);
            }
            log.info("消费成功{}", codeMessage);
        }
    }
}
